package xxljob.autoconfigure;

import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xxljob.exception.AppException;
import xxljob.exception.HttpException;
import xxljob.service.JobInfoService;
import xxljob.service.impl.JobInfoServiceImpl;
import xxljob.util.OkhttpUtil;

import java.io.IOException;
import java.util.HashMap;

@Configuration
@EnableConfigurationProperties(XxlJobAdminProperties.class)
public class XxlJobAdminAutoConfiguration {
    @Autowired
    private XxlJobAdminProperties xxlJobAdminProperties;
    private Logger log = LoggerFactory.getLogger(XxlJobAdminAutoConfiguration.class);
    @Bean
    public JobInfoService jobInfoService() {
        //先登录
        login(xxlJobAdminProperties.getUsername(),xxlJobAdminProperties.getPassword());
        //创建jobinfoService
        return new JobInfoServiceImpl();
    }


    public void login(String username, String password) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userName",username);
        params.put("password",password);
        Response response = OkhttpUtil.postAndResponse(xxlJobAdminProperties.getUrl() + "/login", params, null);
        if (response.code() == 200) {
            try {
                String responseBody = response.body().string();
                JSONObject json = (JSONObject) JSONObject.parse(responseBody);
                if (json.getInteger("code") == 200) {
                    String header = response.header("Set-Cookie");
                    xxlJobAdminProperties.setCookie(header);
                    log.info(">>>>>>>>>>> login success >>>>>>>>>>>>>");
                    log.info("Cookie:"+xxlJobAdminProperties.getCookie());
                }else {
                    throw new AppException("xxl-job-admin login failed，reason= "+json.getString("msg"));
                }
            } catch (IOException e) {
                throw new AppException(e.toString());
            }
        }else {
            throw new HttpException("/login", response.code());
        }
    }
}
